package net.plankton.selectors;

import java.util.ArrayList;
import java.util.List;

import net.plankton.context.Context;

public class Action {

static List<Character> seperators = new ArrayList<Character>();
	
	static {
		seperators.add(':');
		seperators.add('<');
		seperators.add('>');
		seperators.add('=');
	}
	
	public Action(String command) {
		this.command=command;
	}
	
	String command;
	
	public String execute(Context context) {
		int start=0;
		int stop=0;
		String action=null;
		char seperator=' ';
		String argument;
		for (int i=0;i<command.length();i++) {
			if (seperators.contains(command.charAt(i))) {
				if (action==null) {
					action = command.substring(start,i);			
				}
				else {
					argument = command.substring(start,i);
					action = process(action,seperator,argument,context);
				}
				seperator = command.charAt(i);
				start = i+1;
			}
		}
		argument = command.substring(start);
		action = process(action, seperator, argument,context);
		return action;
	}

	private String process(String action, char seperator, String argument, Context context) {
		if (action.equals("tl"))
			action = ""+context.getRiskContext().getThreatLevel();
		
		if (action.equals("num")) {
			return ""+context.getValues(argument).size();
		}
		
		else if (action.equals("store")) {
			context.getValues(argument).add(argument);
			return "stored "+argument;
		}
		else if (seperator=='<') {
			try {
				return ""+(Double.parseDouble(action)<Double.parseDouble(argument));
			}
			catch (Exception e) {
				return ""+(Integer.parseInt(action)<Integer.parseInt(argument));
			}
		}
		else if (seperator=='>') {
			try {
				return ""+(Double.parseDouble(action)>Double.parseDouble(argument));
			}
			catch (Exception e) {
				return ""+(Integer.parseInt(action)>Integer.parseInt(argument));
			}
		}
		else if (seperator=='=') {
			try {
				return ""+(Double.parseDouble(action)==Double.parseDouble(argument));
			}
			catch (Exception e) {
				return ""+(Integer.parseInt(action)==Integer.parseInt(argument));
			}
		}
		return "false";
	}

}
